<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use App\Http\Requests\User\CreateRequest;
use App\Http\Requests\User\UpdateRequest;
use App\User;
use Spatie\Permission\Models\Role;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;

class UserController extends Controller
{

    public function index()
    {
        $user = \Auth::user();
        if (!$user->hasPermissionTo('用户管理')) {
            return view('error.error');
        }
        $users = User::paginate(15);
        return view('users.list', ['users' => $users]);
    }

    public function create()
    {
        $user = \Auth::user();
        if (!$user->hasPermissionTo('用户管理')) {
            return view('error.error');
        }
        $roles = Role::all();
        return view('users.create', ['roles' => $roles]);
    }

    /**
     * @param CreateRequest $request
     * @return \Illuminate\Http\RedirectResponse
     * @throws \Throwable
     */
    public function store(CreateRequest $request)
    {
        $model = \DB::transaction(function () use ($request) {
            $attributes = $request->validated();
            if (!empty($attributes['password'])) {
                $attributes['password'] = bcrypt($attributes['password']);
            }
            $model = User::create($attributes);
            $role = Role::find($attributes['role_id']);
            $model->assignRole($role->name);
            return $model;
        });
        return redirect()->route('users.index');
    }

    public function edit(User $user)
    {
        $users = \Auth::user();
        if (!$users->hasPermissionTo('用户管理')) {
            return view('error.error');
        }
        $roles = Role::all();
        $rolesUser = $user->getRoleNames();

        return view('users.create', [
            'user'      => $user,
            'roles'     => $roles,
            'rolesUser' => $rolesUser->first()
        ]);
    }

    public function update(UpdateRequest $request, User $user)
    {
        $model = \DB::transaction(function () use ($request, $user) {
            $attributes = $request->validated();
            if (empty($attributes['password'])) {
                unset($attributes['password']);
            } else {
                $attributes['password'] = bcrypt($attributes['password']);
            }
            $model = $user->update($attributes);
            $role = Role::find($attributes['role_id']);
            $user->assignRole($role->name);
            return $model;
        });
        return redirect()->route('users.index');
    }
}